import { DebugAccountsFile, DebugManager, EmailFetchProtocol, EmailProperties, FileManager, logger } from '@gal/base';
import { CoremailStore } from '../store/CoremailStore';
import { Context } from '@ohos.arkui.UIContext';
import { common, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

const AppBundleName = "com.gikkiares.maildemo";

export class App {
  p?: EmailProperties
  private _context?: common.UIAbilityContext;

  async init(context: common.UIAbilityContext): Promise<void> {
    this.p = await this.getTestMailProperies();
    this._context = context;
  }

  getAccountList() {
    return Promise.resolve([]);
  }

  getEmailProperty(): EmailProperties {
    if (!this.p) {
      throw new Error();
    }
    return this.p;
  }

  async getTestMailProperies(): Promise<EmailProperties | undefined> {
    if (!DebugManager.emailProperties) {
      let fileName = DebugAccountsFile;
      if (!FileManager.isRawFileExist(DebugAccountsFile)) {
        return undefined;
      }
      let jsonString: string = FileManager.readTextFromRawFileSync(fileName);
      let configs: EmailProperties[] = JSON.parse(jsonString);
      DebugManager.emailProperties = configs;
    }
    let accounts = await this.getAccountList();
    let index = accounts.length;
    if (index >= DebugManager.emailProperties.length) {
      index = DebugManager.emailProperties.length - 1;
    }
    let p = DebugManager.emailProperties[index];
    return p;
  }

  async getTestAccount() {
    let p = await this.getTestMailProperies();
    return p?.userInfo.account ?? "";
  }

  getProtocol(): CoremailStore {
    let p = this.getEmailProperty();
    let store = new CoremailStore(p.coremail!);
    store.init();
    return store;
  }

  async getTestPassword() {
    let config = await this.getTestMailProperies();
    return config?.userInfo.password ?? "";
  }

  login2FACheckHandler: (s: string) => boolean = () => true;

  openAuthWebPage(url: string): void {
    let context = this._context;
    if (context) {
      const want: Want = {
        deviceId: '',
        bundleName: AppBundleName,
        abilityName: 'AuthLoginAbility2',
        parameters:
        { 'authUrl': url }
      }
      context.startAbility(want, (err: BusinessError) => {
        logger.error(err.message);
        // throw err;
      })
    }
  }
}

export const app: App = new App();
